<?php 

if (! function_exists('bchexdec')) {
	function bchexdec($hex)
	{
	    $dec = 0;
	    $len = strlen($hex);
	    for ($i = 1; $i <= $len; $i++) {
	        $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));
	    }
	    return $dec;
	}
}

if (! function_exists('transferInputToValue')) {
	function transferInputToValue($input)
	{
	    return \App\Ethereum::transferInputToValue($input);
	}
}

if (! function_exists('daemonize')) {
	function daemonize() {
		if (! function_exists('pcntl_fork')) {
			throw new \Exception('pcntl extension not loaded');
		}

		$pid = pcntl_fork();

		if ($pid > 0) {
			exit(0);
		} elseif ($pid < 0) {
			throw new \Exception('fork failed');
		}

		posix_setsid();

		$pid = pcntl_fork();

		if ($pid > 0) {
			exit(0);
		} elseif ($pid < 0) {
			throw new \Exception('fork failed');
		}


	}
}

if (! function_exists('install_sigterm_signal_handler')) {
	function install_sigterm_signal_handler() {
		pcntl_signal(SIGTERM, function() {
			$current_pid = posix_getpid();

			$files = Storage::allFiles('pids');

			foreach ($files as $file) {
				$file_info = pathinfo(Storage::path($file));
				list($address, $pid) = explode('-', $file_info['filename']);
				if ($pid == $current_pid) {
					Storage::delete($file);
				}
			}

			exit(0);
		});
	}
}